package tcp_udp;

import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * Author: hu
 * Date: 2023/4/7 14:01
 */
public class UdpServer {
    public static void main(String[] args) throws IOException {
        int count=5;
        // 1. 建立socket连接
        DatagramSocket datagramSocket = new DatagramSocket(514);
        // 2. 创建数据包
        byte[] buffered = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffered, 0, buffered.length);
        // 3. 调用方法接受数据
        while (count-->0) {
            datagramSocket.receive(packet);
            // 4. 解析数据包
            System.out.println(packet.getAddress());
            System.out.println(new String(packet.getData(), 0, packet.getLength()));
        }
            // 5. 关闭资源
            datagramSocket.close();

    }

    @Test
    public void testUDP() throws IOException {
        // 1. 建立socket连接
        DatagramSocket datagramSocket = new DatagramSocket();
        // 2. 创建数据
        String s = "dbmgr hello udp";
        DatagramPacket packet = new DatagramPacket(s.getBytes(), 0, s.getBytes().length, InetAddress.getByName("192.168.2.253"), 514);
        // 3. 调用方法发送
        datagramSocket.send(packet);
        //4. 关闭资源
        datagramSocket.close();
    }

}
